package com.ghck.server.controller;

import java.security.Principal;
import java.util.Map;
import java.util.regex.Pattern;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.ghck.message.service.EasemobService;
import com.ghck.server.GhckAplication;
import com.ghck.server.controller.access.ArgIndexForPrintLog;
import com.ghck.server.exception.GhckException;
import com.ghck.server.exception.ErrorConstant;
import com.ghck.server.model.request.ForgotPassword;
import com.ghck.server.model.request.GenerateVerCode;
import com.ghck.server.model.request.Login;
import com.ghck.server.model.request.Registration;
import com.ghck.server.model.request.ResetPassword;
import com.ghck.server.model.response.Result;
import com.ghck.server.model.response.ResultObject;
import com.ghck.server.service.AjkAccountService;
import com.ghck.server.service.EasemobMessageService;
import com.ghck.server.utils.IntegerUtil;
import com.ghck.server.utils.ValidatorUtil;

@RestController
@RequestMapping("/account")
public class AccountController {
	private final static Logger logger = LoggerFactory.getLogger(AccountController.class);
	
	@Autowired
	AjkAccountService ajkAccountService;
	@Autowired
	private EasemobMessageService easemobMessageService;
	@Autowired
	private EasemobService easemobService;

	/**
	 * 获取短信验证码
	 */
	@PreAuthorize(value=GhckAplication.all)
	@ArgIndexForPrintLog(indexes={0})
	@RequestMapping(value = "/verification_code", method = RequestMethod.POST)
	public Result generateVerificationCode(@RequestBody GenerateVerCode generateVerCode){
		String mobile = generateVerCode.getMobile();
		if (StringUtils.isEmpty(mobile) || !Pattern.matches(ValidatorUtil.mobilePattern, mobile)) {
			GhckException exception = new GhckException(ErrorConstant.OPERATION_ERROR.getErrorCode(),"手机号不能为空或手机号格式错误");
			logger.info("获取验证码失败",exception);
			throw exception;
		}
		ajkAccountService.generateVerificationCode(generateVerCode);

		return new Result();
	}


	/**
	 * 注册
	 */
	@PreAuthorize(value=GhckAplication.all)
	@ArgIndexForPrintLog(indexes={0})
	@RequestMapping(value = "/register", method = RequestMethod.POST)
	public ResultObject<Map<String, Object>> register(@RequestBody Registration registration)
	{
	    String name = registration.getName();
		String mobile = registration.getMobile();
		String verificationCode = registration.getVerificationCode();
		String password = registration.getPassword();
		Integer role = registration.getRole();
		if(StringUtils.isEmpty(name)){
			GhckException exception = new GhckException(ErrorConstant.OPERATION_ERROR.getErrorCode(),"用户名不能为空");
			logger.info("注册用户失败",exception);
			throw exception;
		}
		if (StringUtils.isEmpty(mobile) || !Pattern.matches(ValidatorUtil.mobilePattern, mobile)) {
			GhckException exception = new GhckException(ErrorConstant.OPERATION_ERROR.getErrorCode(),"手机号不能为空或手机号格式错误");
			logger.info("注册用户失败",exception);
			throw exception;
		}
		if(StringUtils.isEmpty(verificationCode)){
			GhckException exception = new GhckException(ErrorConstant.OPERATION_ERROR.getErrorCode(),"验证码不能为空");
			logger.info("注册用户失败",exception);
			throw exception;
		}
		if(StringUtils.isEmpty(password)){
			GhckException exception = new GhckException(ErrorConstant.OPERATION_ERROR.getErrorCode(),"密码不能为空");
			logger.info("注册用户失败",exception);
			throw exception;
		}
		if(!IntegerUtil.isPositiveInteger(role)){
			GhckException exception = new GhckException(ErrorConstant.OPERATION_ERROR.getErrorCode(),"角色不能为空且应大于0");
			logger.info("注册用户失败",exception);
			throw exception;
		}
		Map<String, Object> map = ajkAccountService.register(registration);
		
		return new ResultObject<>(map);
	}

	/**
	 * 登录
	 */
	@PreAuthorize(value=GhckAplication.all)
	@ArgIndexForPrintLog(indexes={0})
	@RequestMapping(value = "/login", method = RequestMethod.POST)
	public ResultObject<Map<String, Object>> login(@RequestBody Login login){
		String mobile = login.getMobile();
		String originPwd = login.getPassword();
		if (StringUtils.isEmpty(mobile) || !Pattern.matches(ValidatorUtil.mobilePattern, mobile)) {
			GhckException exception = new GhckException(ErrorConstant.OPERATION_ERROR.getErrorCode(),"手机号不能为空或手机号格式错误");
			logger.info("登录失败",exception);
			throw exception;
		}
		if(StringUtils.isEmpty(originPwd)){
			GhckException exception = new GhckException(ErrorConstant.OPERATION_ERROR.getErrorCode(),"密码不能为空");
			logger.info("登录失败",exception);
			throw exception;
		}
		Map<String, Object> map = ajkAccountService.login(login);
		return new ResultObject<>(map);
	}

	/**
	 * 找回密码
	 */
	@PreAuthorize(value=GhckAplication.all)
	@ArgIndexForPrintLog(indexes={0})
	@RequestMapping(value = "/forgot_password", method = RequestMethod.POST)
	public ResultObject<Map<String, Object>> forgotPassword(@RequestBody ForgotPassword forgotPassword){
		String mobile = forgotPassword.getMobile();
		String verificationCode = forgotPassword.getVerificationCode();
		String newPassword = forgotPassword.getNewPassword();
		if (StringUtils.isEmpty(mobile) || !Pattern.matches(ValidatorUtil.mobilePattern, mobile)) {
			GhckException exception = new GhckException(ErrorConstant.OPERATION_ERROR.getErrorCode(),"手机号不能为空或手机号格式错误");
			logger.info("找回密码失败",exception);
			throw exception;
		}
		if(StringUtils.isEmpty(verificationCode)){
			GhckException exception = new GhckException(ErrorConstant.OPERATION_ERROR.getErrorCode(),"验证码不能为空");
			logger.info("找回密码失败",exception);
			throw exception;
		}
		if(StringUtils.isEmpty(newPassword)){
			GhckException exception = new GhckException(ErrorConstant.OPERATION_ERROR.getErrorCode(),"新密码不能为空");
			logger.info("找回密码失败",exception);
			throw exception;
		}
		ajkAccountService.forgotPassword(forgotPassword);
		Login login  = new Login();
		login.setMobile(mobile);
		login.setPassword(newPassword);
		Map<String, Object> map = ajkAccountService.login(login);
		
		return new ResultObject<Map<String, Object>>(map);
	}
	

	/**
	 * 修改密码
	 */
	@ArgIndexForPrintLog(indexes={0})
	@RequestMapping(value = "/reset_password", method = RequestMethod.POST)
    @PreAuthorize(value=GhckAplication.admin_customer_service_shop_maker_user)
	public Result resetPassword(@RequestBody ResetPassword resetPassword,Principal principal){
		Integer userId = Integer.parseInt(principal.getName());
		if(!IntegerUtil.isPositiveInteger(userId)){
			GhckException exception = new GhckException(ErrorConstant.OPERATION_ERROR.getErrorCode(),"认证信息错误");
			logger.info("找回密码失败",exception);
			throw exception;
		}
		resetPassword.setUserId(userId);
		String newPassword = resetPassword.getNewPassword();
		String oldPassword = resetPassword.getOldPassword();
		if(StringUtils.isEmpty(newPassword)){
			GhckException exception = new GhckException(ErrorConstant.OPERATION_ERROR.getErrorCode(),"新密码不能为空");
			logger.info("找回密码失败",exception);
			throw exception;
		}
		if(StringUtils.isEmpty(oldPassword)){
			GhckException exception = new GhckException(ErrorConstant.OPERATION_ERROR.getErrorCode(),"旧密码不能为空");
			logger.info("找回密码失败",exception);
			throw exception;
		}
		ajkAccountService.resetPassword(resetPassword);
		return new Result();
	}
	
	/**
	 * 修改密码
	 */
	@ArgIndexForPrintLog(indexes={0})
	@RequestMapping(value = "/ease/add/friend/{friendId}", method = RequestMethod.GET)
    @PreAuthorize(value=GhckAplication.admin_customer_service_shop_maker_user)
	public ResultObject<String> getEaseFriend(@PathVariable("friendId") Integer friendId,Principal principal){
		Integer userId = Integer.parseInt(principal.getName());
		if(!IntegerUtil.isPositiveInteger(userId)){
			GhckException exception = new GhckException(ErrorConstant.OPERATION_ERROR.getErrorCode(),"未登录,请先登录");
			throw exception;
		}
		if(null == friendId || friendId == 0){
			GhckException exception = new GhckException(ErrorConstant.OPERATION_ERROR.getErrorCode(),"好友ID不能为空");
			throw exception;
		}
		String addResult = easemobService.addFriend(String.valueOf(userId), String.valueOf(friendId));
		return new ResultObject<String>(addResult);
	}

}
